package top.tagao.yygh.hosp.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.tagao.yygh.common.rabbit.constant.MqConst;
import top.tagao.yygh.common.rabbit.service.RabbitService;
import top.tagao.yygh.hosp.service.ScheduleService;
import top.tagao.yygh.model.hosp.Schedule;
import top.tagao.yygh.vo.msm.MsmVo;
import top.tagao.yygh.vo.order.OrderMqVo;

import java.io.IOException;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/14 19:36
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;


    @RabbitListener(bindings = @QueueBinding(
                        value = @Queue(value = MqConst.QUEUE_ORDER, durable  = "true"),
                        exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
                        key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException{
        // 1. 下单成功更新预约数,更新排班剩余预约数
        if(null != orderMqVo.getAvailableNumber()) {
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        }else {
            //取消预约更新预约数,更新排班剩余预约数
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber() + 1;
            schedule.setAvailableNumber(availableNumber);
            scheduleService.update(schedule);
        }

        // 2. 发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        }

    }

}
